<template>
  <view class="red-packet-release-page">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-back" @click="navigateBack">
        <uni-icons type="back" size="28" color="#333"></uni-icons>
      </view>
      <view class="nav-title">{{ navTitle }}</view>
      <view class="nav-empty"></view> <!-- 占位，保持标题居中 -->
    </view>

    <!-- 红包类型切换Tabs -->
    <view class="packet-type-tabs">
      <view 
        v-for="(type, index) in packetTypeList" 
        :key="index"
        class="tab-item"
        :class="{ active: selectedType === type.value }"
        @click="switchPacketType(type.value)"
        v-if="!type.hide"
      >
        <text class="tab-text">{{ type.label }}</text>
      </view>
    </view>

    <!-- 表单容器 -->
    <form class="packet-form" @submit="handleSubmit">
      <!-- 1. 通用金额配置（所有类型共用） -->
      <view class="form-section">
        <!-- 总金额 -->
        <view class="form-item">
          <view class="item-label">总金额</view>
          <view class="item-input">
            <text class="money-symbol">¥</text>
            <input 
              type="number" 
              placeholder="请输入总金额（≥20元）" 
              v-model.number="formData.totalAmount"
              @input="handleAmountInput"
              placeholder-style="color:#999"
            >
            </input>
          </view>
          <view class="item-tip" v-if="formTips.totalAmount">{{ formTips.totalAmount }}</view>
        </view>

        <!-- 红包个数（个人红包默认1，不可改） -->
        <view class="form-item" v-if="selectedType !== 'personal'">
          <view class="item-label">红包个数</view>
          <view class="item-input">
            <input 
              type="number" 
              placeholder="请输入个数（≥1）" 
              v-model.number="formData.totalCount"
              @input="handleCountInput"
              placeholder-style="color:#999"
            >
            </input>
          </view>
          <view class="item-tip" v-if="formTips.totalCount">{{ formTips.totalCount }}</view>
        </view>

        <!-- 单个金额类型（固定/随机） -->
        <view class="form-item">
          <view class="item-label">金额类型</view>
          <view class="item-radio-group">
            <label class="radio-label" @click="formData.singleType = 'fixed'">
              <radio value="fixed" :checked="formData.singleType === 'fixed'" />
              <text class="radio-text">固定金额</text>
            </label>
            <label class="radio-label" @click="formData.singleType = 'random'">
              <radio value="random" :checked="formData.singleType === 'random'" />
              <text class="radio-text">随机金额</text>
            </label>
          </view>
        </view>

        <!-- 固定金额输入（singleType=fixed时显示） -->
        <view class="form-item" v-if="formData.singleType === 'fixed' && selectedType !== 'personal'">
          <view class="item-label">单个金额</view>
          <view class="item-input">
            <text class="money-symbol">¥</text>
            <input 
              type="number" 
              placeholder="请输入单个金额" 
              v-model.number="formData.fixedSingleAmount"
              @input="handleFixedAmountInput"
              placeholder-style="color:#999"
            >
            </input>
          </view>
          <view class="item-tip" v-if="formTips.fixedSingleAmount">{{ formTips.fixedSingleAmount }}</view>
        </view>

        <!-- 随机金额范围（singleType=random时显示） -->
        <view class="form-item" v-if="formData.singleType === 'random'">
          <view class="item-label">金额范围</view>
          <view class="item-range-input">
            <view class="range-item">
              <text class="money-symbol">¥</text>
              <input 
                type="number" 
                placeholder="从" 
                v-model.number="formData.randomRange.min"
                @input="handleRandomMinInput"
                placeholder-style="color:#999"
              >
              </input>
            </view>
            <view class="range-separator">至</view>
            <view class="range-item">
              <text class="money-symbol">¥</text>
              <input 
                type="number" 
                placeholder="到" 
                v-model.number="formData.randomRange.max"
                @input="handleRandomMaxInput"
                placeholder-style="color:#999"
              >
              </input>
            </view>
          </view>
          <view class="item-tip" v-if="formTips.randomRange">{{ formTips.randomRange }}</view>
        </view>
      </view>

      <!-- 2. 群红包专属配置（拼手气/普通） -->
      <view class="form-section" v-if="selectedType === 'group'">
        <view class="form-item">
          <view class="item-label">群红包类型</view>
          <view class="item-radio-group">
            <label class="radio-label" @click="formData.groupType = 'lucky'">
              <radio value="lucky" :checked="formData.groupType === 'lucky'" />
              <text class="radio-text">拼手气红包</text>
            </label>
            <label class="radio-label" @click="formData.groupType = 'normal'">
              <radio value="normal" :checked="formData.groupType === 'normal'" />
              <text class="radio-text">普通红包</text>
            </label>
          </view>
        </view>
      </view>

      <!-- 3. 位置红包专属配置 -->
      <view class="form-section" v-if="selectedType === 'location'">
        <!-- 选择位置 -->
        <view class="form-item" @click="chooseLocation">
          <view class="item-label">目标位置</view>
          <view class="item-select">
            <text class="select-text">{{ formData.locationConfig.selectedAddress || '点击选择位置' }}</text>
            <uni-icons type="right" size="20" color="#999"></uni-icons>
          </view>
          <view class="item-tip" v-if="formTips.location">{{ formTips.location }}</view>
        </view>

        <!-- 可见范围 -->
        <view class="form-item">
          <view class="item-label">可见范围</view>
          <view class="item-picker" @click="showRangePicker = true">
            <text class="picker-text">{{ formData.locationConfig.visibleRangeLabel }}</text>
            <uni-icons type="right" size="20" color="#999"></uni-icons>
          </view>
          <picker 
            mode="selector" 
            :range="rangeOptions" 
            :value="rangeIndex"
            @change="handleRangeChange"
            v-if="showRangePicker"
          ></picker>
        </view>

        <!-- 停留秒数 -->
        <view class="form-item">
          <view class="item-label">停留秒数</view>
          <view class="item-input">
            <input 
              type="number" 
              placeholder="请输入停留秒数（≥1）" 
              v-model.number="formData.locationConfig.staySeconds"
              @input="handleStaySecondsInput"
              placeholder-style="color:#999"
            >
            </input>
            <text class="unit-text">秒</text>
          </view>
          <view class="item-tip" v-if="formTips.staySeconds">{{ formTips.staySeconds }}</view>
        </view>

        <!-- 跳转页面编码 -->
        <view class="form-item">
          <view class="item-label">跳转页面编码</view>
          <view class="item-input">
            <input 
              type="text" 
              placeholder="如 PAGE_001" 
              v-model="formData.locationConfig.jumpPageCode"
              @input="handlePageCodeInput"
              placeholder-style="color:#999"
            >
            </input>
          </view>
          <view class="item-tip" v-if="formTips.jumpPageCode">{{ formTips.jumpPageCode }}</view>
        </view>
      </view>

      <!-- 4. 广告红包专属配置 -->
      <view class="form-section" v-if="selectedType === 'ad'">
        <!-- 广告标题 -->
        <view class="form-item">
          <view class="item-label">广告标题</view>
          <view class="item-input">
            <input 
              type="text" 
              placeholder="请输入广告标题（≤30字）" 
              v-model="formData.adConfig.adTitle"
              @input="handleAdTitleInput"
              placeholder-style="color:#999"
            >
            </input>
          </view>
          <view class="item-tip" v-if="formTips.adTitle">{{ formTips.adTitle }}</view>
        </view>

        <!-- 广告媒体上传（图片/视频） -->
        <view class="form-item">
          <view class="item-label">广告媒体</view>
          <view class="item-upload">
            <view class="upload-btn" @click="chooseMedia">
              <uni-icons type="plus" size="24" color="#666"></uni-icons>
              <text class="upload-text">上传图片/视频</text>
            </view>
            <!-- 媒体预览 -->
            <view class="media-preview" v-if="formData.adConfig.adMedia.url">
              <image 
                v-if="formData.adConfig.adMedia.type === 'image'"
                :src="formData.adConfig.adMedia.url"
                class="preview-image"
                mode="aspectFill"
              ></image>
              <view v-else class="preview-video">
                <video :src="formData.adConfig.adMedia.url" class="video-player" controls></video>
              </view>
              <view class="preview-delete" @click="deleteMedia">
                <uni-icons type="close" size="20" color="#fff"></uni-icons>
              </view>
            </view>
          </view>
          <view class="item-tip" v-if="formTips.adMedia">{{ formTips.adMedia }}</view>
        </view>

        <!-- 跳转页面编码 -->
        <view class="form-item">
          <view class="item-label">跳转页面编码</view>
          <view class="item-input">
            <input 
              type="text" 
              placeholder="如 PAGE_SHOP_123" 
              v-model="formData.adConfig.jumpPageCode"
              @input="handleAdPageCodeInput"
              placeholder-style="color:#999"
            >
            </input>
          </view>
          <view class="item-tip" v-if="formTips.adPageCode">{{ formTips.adPageCode }}</view>
        </view>

        <!-- 限定位置（可选） -->
        <view class="form-item">
          <label class="checkbox-label" @click="formData.adConfig.limitLocation = !formData.adConfig.limitLocation">
            <checkbox :checked="formData.adConfig.limitLocation" />
            <text class="checkbox-text">限定领取位置</text>
          </label>
        </view>

        <!-- 限定位置配置（勾选后显示） -->
        <view class="form-section-inner" v-if="formData.adConfig.limitLocation">
          <view class="form-item" @click="chooseAdLocation">
            <view class="item-label">限定位置</view>
            <view class="item-select">
              <text class="select-text">{{ formData.adConfig.locationConfig.selectedAddress || '点击选择位置' }}</text>
              <uni-icons type="right" size="20" color="#999"></uni-icons>
            </view>
          </view>
          <view class="form-item">
            <view class="item-label">可见范围</view>
            <view class="item-picker" @click="showAdRangePicker = true">
              <text class="picker-text">{{ formData.adConfig.locationConfig.visibleRangeLabel }}</text>
              <uni-icons type="right" size="20" color="#999"></uni-icons>
            </view>
            <picker 
              mode="selector" 
              :range="rangeOptions" 
              :value="adRangeIndex"
              @change="handleAdRangeChange"
              v-if="showAdRangePicker"
            ></picker>
          </view>
        </view>

        <!-- 领取条件 -->
        <view class="form-item">
          <view class="item-label">领取条件</view>
          <view class="item-radio-group">
            <label class="radio-label" @click="formData.adConfig.receiveCondition.type = 'watchFull'">
              <radio value="watchFull" :checked="formData.adConfig.receiveCondition.type === 'watchFull'" />
              <text class="radio-text">完整观看广告</text>
            </label>
            <label class="radio-label" @click="formData.adConfig.receiveCondition.type = 'staySeconds'">
              <radio value="staySeconds" :checked="formData.adConfig.receiveCondition.type === 'staySeconds'" />
              <text class="radio-text">停留秒数</text>
            </label>
          </view>
        </view>

        <!-- 停留秒数（条件为staySeconds时显示） -->
        <view class="form-item" v-if="formData.adConfig.receiveCondition.type === 'staySeconds'">
          <view class="item-label">停留秒数</view>
          <view class="item-input">
            <input 
              type="number" 
              placeholder="请输入停留秒数（≥1）" 
              v-model.number="formData.adConfig.receiveCondition.staySeconds"
              @input="handleAdStaySecondsInput"
              placeholder-style="color:#999"
            >
            </input>
            <text class="unit-text">秒</text>
          </view>
        </view>
      </view>

      <!-- 5. 祝福语（所有类型共用） -->
      <view class="form-section">
        <view class="form-item">
          <view class="item-label">祝福语</view>
          <view class="item-input">
            <input 
              type="text" 
              :placeholder="defaultBlessing" 
              v-model="formData.blessingText"
              placeholder-style="color:#999"
            >
            </input>
          </view>
        </view>
      </view>

      <!-- 底部支付按钮 -->
      <view class="form-submit">
        <button 
          form-type="submit" 
          class="submit-btn"
          :disabled="!formValid"
        >
          {{ submitBtnText }}
        </button>
        <view class="submit-tip">
          <text>支付方式：余额支付（当前余额：¥{{ userBalance.toFixed(2) }}</text>
        </view>
      </view>
    </form>

    <!-- 地图选点弹窗（位置红包/广告红包限定位置时使用） -->
    <view class="map-modal" v-if="showMapModal">
      <view class="map-header">
        <text class="map-title">选择位置</text>
        <uni-icons type="close" size="24" color="#666" @click="closeMapModal"></uni-icons>
      </view>
      <view class="map-container">
        <map 
          class="map"
          :latitude="mapLatitude"
          :longitude="mapLongitude"
          :show-location="true"
          :enable-zoom="true"
          :enable-scroll="true"
          @tap="confirmMapLocation"
        ></map>
        <!-- 定位图标 -->
        <view class="map-marker">
          <image src="/static/location.png" class="marker-icon" mode="aspectFit"></image>
        </view>
      </view>
      <view class="map-footer">
        <button class="map-confirm-btn" @click="confirmMapLocation">确认选择</button>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex';
const redPacket =uniCloud.importObject('RedPacketCloud',{customUI:true})
import { location2address } from '../../utils/getPois';

export default {
  data() {
    return {
      // 红包类型配置（含权限控制）
      packetTypeList: [
        { label: '个人红包', value: 'personal', hide: false },
        { label: '群红包', value: 'group', hide: false },
        { label: '位置红包', value: 'location', hide: false },
        { label: '广告红包', value: 'ad', hide: true } // 默认普通用户隐藏，商户显示
      ],
      selectedType: 'personal', // 当前选中的红包类型
      formData: {
        // 通用配置
        totalAmount: 0,
        totalCount: 1, // 个人红包默认1，不可改
        singleType: 'fixed', // fixed/random
        fixedSingleAmount: 0,
        randomRange: { min: 0.01, max: 10 },
        blessingText: '',

        // 群红包配置
        groupType: 'lucky', // lucky/normal

        // 位置红包配置
        locationConfig: {
          targetLocation: null, // { latitude, longitude }
          selectedAddress: '', // 选择的地址文本
          visibleRange: 1000, // 单位：米
          visibleRangeLabel: '1公里',
          staySeconds: 10,
          jumpPageCode: ''
        },

        // 广告红包配置
        adConfig: {
          adTitle: '',
          adMedia: { type: 'image', url: '', size: 0 }, // type:image/video
          jumpPageCode: '',
          limitLocation: false, // 是否限定位置
          locationConfig: {
            targetLocation: null,
            selectedAddress: '',
            visibleRange: 1000,
            visibleRangeLabel: '1公里'
          },
          receiveCondition: {
            type: 'staySeconds', // watchFull/staySeconds
            staySeconds: 10
          }
        }
      },

      // 表单校验相关
      formTips: {}, // 错误提示
      formValid: false, // 表单是否有效

      // 选择器配置
      rangeOptions: ['500米', '1公里', '3公里', '5公里', '10公里'],
      rangeIndex: 1, // 默认1公里
      adRangeIndex: 1,
      showRangePicker: false,
      showAdRangePicker: false,

      // 地图相关
      showMapModal: false,
      mapLatitude: 39.9042, // 默认北京纬度
      mapLongitude: 116.4074, // 默认北京经度
      isAdLocation: false, // 是否是广告红包的位置选择

      // 用户信息（从vuex获取）
      userBalance: 0
    };
  },
  computed: {
    // 导航标题（根据选中类型变化）
    navTitle() {
      const titleMap = {
        personal: '发个人红包',
        group: '发群红包',
        location: '发位置红包',
        ad: '发放广告红包'
      };
      return titleMap[this.selectedType];
    },

    // 默认祝福语（根据类型变化）
    defaultBlessing() {
      const blessingMap = {
        personal: '恭喜发财，大吉大利',
        group: '恭喜发财，大吉大利',
        location: '路过的小伙伴，快来领红包啦！',
        ad: '看广告领红包，福利多多～'
      };
      return blessingMap[this.selectedType];
    },

    // 提交按钮文本
    submitBtnText() {
      return this.selectedType === 'ad' ? '支付并发布广告' : '塞钱进红包';
    },

    // 从vuex获取用户信息（用户类型、余额）
    ...mapState({
      userInfo: state => state.msg.user,
      userType: state => state.msg.user.userType
    })
  },
  onLoad(options) {
    // 1. 初始化：商户用户显示广告红包选项
    if (this.userType === 'merchant') {
      this.packetTypeList.find(item => item.value === 'ad').hide = false;
    }

    // 2. 群红包场景：从参数获取群ID
    if (options.groupId) {
      this.formData.targetId = options.groupId;
      this.selectedType = 'group'; // 自动切换到群红包
    }

    // 3. 获取用户余额
    this.getUserBalance();
  },
  methods: {
    // 返回上一页
    navigateBack() {
      uni.navigateBack({ delta: 1 });
    },

    // 切换红包类型
    switchPacketType(type) {
      this.selectedType = type;
      // 重置表单校验提示
      this.formTips = {};
      // 个人红包强制设置个数为1
      if (type === 'personal') {
        this.formData.totalCount = 1;
      }
    },

    // 获取用户余额（调用云对象或接口）
    async getUserBalance() {
				console.log("用户信息",this.userInfo);
      try {
        const db = uniCloud.database();

        const userRes = await db.collection('linli-user').doc(this.userInfo._id).field({ balance: true }).get();
		console.log("余额",userRes);
        this.userBalance = userRes.result.data[0].balance || 0;
      } catch (err) {
        uni.showToast({ title: '获取余额失败', icon: 'none' });
        console.error('getUserBalance error:', err);
      }
    },

    // 金额输入校验
    handleAmountInput() {
      const { totalAmount } = this.formData;
      if (totalAmount < 20) {
        this.formTips.totalAmount = '总金额不得小于20元';
      } else if (totalAmount > 10000) { // 限制最大金额（可自定义）
        this.formTips.totalAmount = '总金额不得超过10000元';
      } else {
        this.formTips.totalAmount = '';
      }
      this.checkFormValid();
    },

    // 个数输入校验
    handleCountInput() {
      const { totalCount } = this.formData;
      if (totalCount < 1) {
        this.formTips.totalCount = '红包个数不得小于1';
      } else if (totalCount > 100) { // 限制最大个数
        this.formTips.totalCount = '红包个数不得超过100';
      } else {
        this.formTips.totalCount = '';
      }
      this.checkFormValid();
    },

    // 固定金额校验
    handleFixedAmountInput() {
      const { fixedSingleAmount, totalAmount, totalCount } = this.formData;
      if (fixedSingleAmount <= 0) {
        this.formTips.fixedSingleAmount = '单个金额不得小于0';
      } else if (fixedSingleAmount * totalCount !== totalAmount) {
        this.formTips.fixedSingleAmount = `单个金额×个数应等于总金额（${totalAmount}元）`;
      } else {
        this.formTips.fixedSingleAmount = '';
      }
      this.checkFormValid();
    },

    // 随机金额最小值校验
    handleRandomMinInput() {
      const { min, max } = this.formData.randomRange;
      if (min <= 0) {
        this.formTips.randomRange = '最小值不得小于0.01元';
      } else if (min >= max) {
        this.formTips.randomRange = '最小值不得大于等于最大值';
      } else {
        this.formTips.randomRange = '';
      }
      this.checkFormValid();
    },

    // 随机金额最大值校验
    handleRandomMaxInput() {
      this.handleRandomMinInput(); // 复用最小值校验逻辑
    },

    // 位置红包-停留秒数校验
    handleStaySecondsInput() {
      const { staySeconds } = this.formData.locationConfig;
      if (staySeconds < 1) {
        this.formTips.staySeconds = '停留秒数不得小于1';
      } else {
        this.formTips.staySeconds = '';
      }
      this.checkFormValid();
    },

    // 位置红包-页面编码校验
    handlePageCodeInput() {
      const { jumpPageCode } = this.formData.locationConfig;
      if (!jumpPageCode) {
        this.formTips.jumpPageCode = '请输入跳转页面编码';
      } else {
        this.formTips.jumpPageCode = '';
      }
      this.checkFormValid();
    },

    // 广告标题校验
    handleAdTitleInput() {
      const { adTitle } = this.formData.adConfig;
      if (!adTitle) {
        this.formTips.adTitle = '请输入广告标题';
      } else if (adTitle.length > 30) {
        this.formTips.adTitle = '广告标题不得超过30字';
      } else {
        this.formTips.adTitle = '';
      }
      this.checkFormValid();
    },

    // 广告媒体选择
    chooseMedia() {
      uni.chooseMedia({
        count: 1,
        mediaType: ['image', 'video'],
        sourceType: ['album', 'camera'],
        maxDuration: 30, // 视频最大时长30秒
        success: (res) => {
          const media = res.tempFiles[0];
          this.formData.adConfig.adMedia = {
            type: media.type,
            url: media.tempFilePath,
            size: media.size
          };
          this.formTips.adMedia = '';
          this.checkFormValid();
        },
        fail: () => {
          this.formTips.adMedia = '媒体选择失败，请重试';
        }
      });
    },

    // 删除广告媒体
    deleteMedia() {
      this.formData.adConfig.adMedia = { type: 'image', url: '', size: 0 };
      this.formTips.adMedia = '请上传广告媒体';
      this.checkFormValid();
    },

    // 广告页面编码校验
    handleAdPageCodeInput() {
      const { jumpPageCode } = this.formData.adConfig;
      if (!jumpPageCode) {
        this.formTips.adPageCode = '请输入跳转页面编码';
      } else {
        this.formTips.adPageCode = '';
      }
      this.checkFormValid();
    },

    // 广告停留秒数校验
    handleAdStaySecondsInput() {
      const { staySeconds } = this.formData.adConfig.receiveCondition;
      if (staySeconds < 1) {
        this.formTips.adStaySeconds = '停留秒数不得小于1';
      } else {
        this.formTips.adStaySeconds = '';
      }
      this.checkFormValid();
    },

    // 打开地图选点（位置红包）
    chooseLocation() {
      this.isAdLocation = false;
      this.openMapModal();
    },

    // 打开地图选点（广告红包限定位置）
    chooseAdLocation() {
      this.isAdLocation = true;
      this.openMapModal();
    },

    // 打开地图弹窗并获取当前位置
    openMapModal() {
      this.showMapModal = true;
      // 获取用户当前位置
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          this.mapLatitude = res.latitude;
          this.mapLongitude = res.longitude;
          // 逆地理编码获取地址文本
          this.getAddressByLocation(res.latitude, res.longitude);
        },
        fail: () => {
          uni.showToast({ title: '获取位置失败，请手动选择', icon: 'none' });
        }
      });
    },

    // 关闭地图弹窗
    closeMapModal() {
      this.showMapModal = false;
    },

    // 逆地理编码（经纬度转地址）
    async getAddressByLocation(latitude, longitude) {
      try {
       const res=await   location2address({latitude, longitude})
        const address = res.address || '未知地址';
        if (this.isAdLocation) {
          this.formData.adConfig.locationConfig.selectedAddress = address;
          this.formData.adConfig.locationConfig.targetLocation = { latitude, longitude };
        } else {
          this.formData.locationConfig.selectedAddress = address;
          this.formData.locationConfig.targetLocation = { latitude, longitude };
        }
        this.formTips.location = '';
      } catch (err) {
        this.formTips.location = '地址解析失败，请重试';
        console.error('getAddressByLocation error:', err);
      }
    },

    // 确认地图位置
    confirmMapLocation() {
      this.getAddressByLocation(this.mapLatitude, this.mapLongitude);
      this.closeMapModal();
      this.checkFormValid();
    },

    // 可见范围选择（位置红包）
    handleRangeChange(e) {
      const index = e.detail.value;
      this.rangeIndex = index;
      const rangeMap = [500, 1000, 3000, 5000, 10000];
      this.formData.locationConfig.visibleRange = rangeMap[index];
      this.formData.locationConfig.visibleRangeLabel = this.rangeOptions[index];
      this.showRangePicker = false;
    },

    // 可见范围选择（广告红包）
    handleAdRangeChange(e) {
      const index = e.detail.value;
      this.adRangeIndex = index;
      const rangeMap = [500, 1000, 3000, 5000, 10000];
      this.formData.adConfig.locationConfig.visibleRange = rangeMap[index];
      this.formData.adConfig.locationConfig.visibleRangeLabel = this.rangeOptions[index];
      this.showAdRangePicker = false;
    },

    // 校验表单是否有效
    checkFormValid() {
      let valid = true;

      // 1. 通用校验：总金额、个数
      if (this.formData.totalAmount < 20 || this.formTips.totalAmount) valid = false;
      if (this.selectedType !== 'personal' && (this.formData.totalCount < 1 || this.formTips.totalCount)) valid = false;

      // 2. 金额类型校验
      if (this.formData.singleType === 'fixed' && this.selectedType !== 'personal') {
        if (this.formTips.fixedSingleAmount) valid = false;
      }
      if (this.formData.singleType === 'random' && this.formTips.randomRange) valid = false;

      // 3. 位置红包专属校验
      if (this.selectedType === 'location') {
        if (!this.formData.locationConfig.targetLocation) {
          this.formTips.location = '请选择目标位置';
          valid = false;
        }
        if (this.formTips.staySeconds || !this.formData.locationConfig.jumpPageCode) valid = false;
      }

      // 4. 广告红包专属校验
      if (this.selectedType === 'ad') {
        if (this.formTips.adTitle || !this.formData.adConfig.adMedia.url) valid = false;
        if (!this.formData.adConfig.jumpPageCode) valid = false;
        if (this.formData.adConfig.receiveCondition.type === 'staySeconds' && this.formData.adConfig.receiveCondition.staySeconds < 1) valid = false;
        if (this.formData.adConfig.limitLocation && !this.formData.adConfig.locationConfig.targetLocation) valid = false;
      }

      this.formValid = valid;
    },

    // 提交表单（创建红包）
    async handleSubmit(e) {
      e.preventDefault();
      this.checkFormValid();
      if (!this.formValid) return;

      // 1. 构造云对象参数
      const params = {
        packetType: this.selectedType,
        sendUserId: this.userInfo.id,
        targetId: this.formData.targetId || null,
        totalAmount: this.formData.totalAmount,
        totalCount: this.formData.totalCount,
        singleType: this.formData.singleType,
        blessingText: this.formData.blessingText || this.defaultBlessing
      };

      // 2. 补充不同类型的专属参数
      if (this.formData.singleType === 'fixed') {
        params.fixedSingleAmount = this.formData.fixedSingleAmount;
      } else {
        params.randomRange = this.formData.randomRange;
      }
      if (this.selectedType === 'location') {
        params.locationConfig = {
          targetLocation: this.formData.locationConfig.targetLocation,
          visibleRange: this.formData.locationConfig.visibleRange,
          staySeconds: this.formData.locationConfig.staySeconds,
          jumpPageCode: this.formData.locationConfig.jumpPageCode
        };
      }
      if (this.selectedType === 'ad') {
        params.adConfig = {
          adTitle: this.formData.adConfig.adTitle,
          adMedia: this.formData.adConfig.adMedia,
          jumpPageCode: this.formData.adConfig.jumpPageCode,
          limitLocation: this.formData.adConfig.limitLocation,
          receiveCondition: this.formData.adConfig.receiveCondition
        };
        if (this.formData.adConfig.limitLocation) {
          params.adConfig.locationConfig = this.formData.adConfig.locationConfig;
        }
      }

      // 3. 调用云对象创建红包
      uni.showLoading({ title: '创建红包中...' });
      try {
        const redPacketCloud = uniCloud.importObject('RedPacketCloud');
        const res = await redPacketCloud.createRedPacket(params);
        if (res.success) {
          // 4. 跳转支付页面（携带红包ID）
          uni.navigateTo({
            url: `/pages/red-packet/pay?redPacketId=${res.data.redPacketId}&totalAmount=${this.formData.totalAmount}`
          });
        } else {
          uni.showToast({ title: res.msg || '创建红包失败', icon: 'none' });
        }
      } catch (err) {
        uni.showToast({ title: '系统错误，请重试', icon: 'none' });
        console.error('createRedPacket error:', err);
      } finally {
        uni.hideLoading();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
/* 页面容器 */
.red-packet-release-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f8f8f8;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}
.nav-back {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.nav-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}
.nav-empty {
  width: 40rpx;
  height: 40rpx;
}

/* 红包类型Tabs */
.packet-type-tabs {
  display: flex;
  overflow-x: auto;
  background-color: #fff;
  padding: 0 20rpx;
}
.tab-item {
  flex: 0 0 auto;
  padding: 20rpx 30rpx;
  position: relative;
}
.tab-text {
  font-size: 28rpx;
  color: #666;
}
.tab-item.active .tab-text {
  color: #07c160;
  font-weight: 500;
}
.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 30rpx;
  right: 30rpx;
  height: 4rpx;
  background-color: #07c160;
  border-radius: 2rpx;
}

/* 表单容器 */
.packet-form {
  padding: 20rpx 30rpx;
}
.form-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}
.form-item {
  display: flex;
  flex-direction: column;
  margin-bottom: 24rpx;
}
.form-item:last-child {
  margin-bottom: 0;
}
.item-label {
  font-size: 26rpx;
  color: #333;
  margin-bottom: 8rpx;
}
.item-input {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 12rpx;
  padding: 16rpx 20rpx;
}
.money-symbol {
  font-size: 28rpx;
  color: #666;
  margin-right: 8rpx;
}
input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  background: transparent;
}
input::placeholder {
  color: #999;
}
.item-tip {
  font-size: 22rpx;
  color: #ff4d4f;
  margin-top: 8rpx;
}

/* 单选组样式 */
.item-radio-group {
  display: flex;
  gap: 40rpx;
  padding: 8rpx 0;
}
.radio-label {
  display: flex;
  align-items: center;
  gap: 8rpx;
  font-size: 26rpx;
  color: #333;
}
radio {
  transform: scale(0.8);
}

/* 范围输入样式 */
.item-range-input {
  display: flex;
  align-items: center;
  gap: 16rpx;
  background-color: #f5f5f5;
  border-radius: 12rpx;
  padding: 16rpx 20rpx;
}
.range-item {
  flex: 1;
  display: flex;
  align-items: center;
}
.range-separator {
  font-size: 28rpx;
  color: #666;
}

/* 选择器样式 */
.item-picker {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #f5f5f5;
  border-radius: 12rpx;
  padding: 16rpx 20rpx;
}
.picker-text {
  font-size: 28rpx;
  color: #333;
}

/* 单位文本样式 */
.unit-text {
  font-size: 28rpx;
  color: #666;
  margin-left: 8rpx;
}

/* 复选框样式 */
.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8rpx;
  font-size: 26rpx;
  color: #333;
  padding: 8rpx 0;
}
checkbox {
  transform: scale(0.8);
}

/* 内部表单区域（广告红包限定位置） */
.form-section-inner {
  margin-top: 16rpx;
  padding-top: 16rpx;
  border-top: 1px solid #f0f0f0;
}

/* 媒体上传样式 */
.item-upload {
  display: flex;
  align-items: flex-start;
  gap: 20rpx;
}
.upload-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 120rpx;
  height: 120rpx;
  border: 2rpx dashed #ddd;
  border-radius: 12rpx;
  background-color: #fafafa;
}
.upload-text {
  font-size: 22rpx;
  color: #999;
  margin-top: 8rpx;
}
.media-preview {
  position: relative;
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  overflow: hidden;
}
.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.preview-video {
  width: 100%;
  height: 100%;
}
.preview-delete {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  width: 36rpx;
  height: 36rpx;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 提交按钮样式 */
.form-submit {
  margin-top: 40rpx;
}
.submit-btn {
  width: 100%;
  height: 90rpx;
  background-color: #07c160;
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.submit-btn:disabled {
  background-color: #a7e8c5;
}
.submit-tip {
  text-align: center;
  font-size: 22rpx;
  color: #999;
  margin-top: 16rpx;
}

/* 地图弹窗样式 */
.map-modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: #fff;
  z-index: 9999;
  display: flex;
  flex-direction: column;
}
.map-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #f0f0f0;
}
.map-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}
.map-container {
  flex: 1;
  position: relative;
}
.map {
  width: 100%;
  height: 100%;
}
.map-marker {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -100%);
  width: 48rpx;
  height: 48rpx;
}
.marker-icon {
  width: 100%;
  height: 100%;
}
.map-footer {
  padding: 20rpx 30rpx;
  border-top: 1px solid #f0f0f0;
}
.map-confirm-btn {
  width: 100%;
  height: 80rpx;
  background-color: #07c160;
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
}
</style>